<template>
	<view class="pageContent" :style="{height: pageConfig.scrollHeight}" style="overflow: hidden;">
		<z-paging ref="paging" v-model="tableData" @query="getTableDataFun" :auto="false" :fixed="false"
			use-virtual-list auto-show-back-to-top :back-to-top-style="{ 'opacity':0.6 }" :topZIndex="99999"
			:bottomZIndex="999999">
			<template #top>
				<up-navbar title="审批待办" style="z-index: 99;" left-icon="" :autoBack="false" :fixed="false"
					:safeAreaInsetTop="true">
				</up-navbar>

				<view class="search x-bc">
					<up-search placeholder="请输入关键字" v-model="searchKey" shape="square" @search="search"
						:animation="false" :actionStyle="{color:'#fff'}" @clear="refreshPage">
						<template #action>
							<view class="x-c">
								<up-icon v-if="!uni.$utils.isPda()" name="scan" color="#fff" size="30"
									@click="searchScanBtn"></up-icon>
							</view>
						</template>
					</up-search>
				</view>

				<z-tabs ref="tabs" unit="px" scroll-count="3" active-color="#51d0d0" :list="tabList" :current="current"
					@change="tabsChange">

					<template #right>
						<view class="x-ec">


							<view class="x-c" style="padding: 0 10px;border-left: 1px solid #e8e8e8;font-size: 12px;"
								v-if="!source">

								<view class="f-dc" style="min-width: 36px;zoom: 0.6;">
									<text>自动</text>
									<text>下一个</text>
								</view>

								<switch :checked="approveWaitToOpenNext" @change="switchChange" color="#1cd842"
									style="zoom: 0.6;"></switch>
							</view>


							<m-dropdown-menu class="drag" ref="filterMenu" marginTop="10" zIndex="9999">
								<template #default="{element}">
									<view class="x-c" style="width: 50px;border-left: 1px solid #e8e8e8;">
										<uni-icons fontFamily="CustomFontPlatform" color="#818181"
											:size="20">{{uni.$utils.toUniCode('&#xe6cb;')}}</uni-icons>
									</view>
								</template>

								<template #Card>
									<view style="background-color: #fff;">
										<m-date-time mode="module" :initData="DropDowmMenu_Date" title="单据日期"
											@confirm="DateSubmit($event)" @reset="onDateReset">
										</m-date-time>

									</view>
								</template>
							</m-dropdown-menu>
						</view>
					</template>
				</z-tabs>
			</template>


		</z-paging>
	</view>
</template>

<script setup lang="ts" name="todo">
	import { ref, onMounted, onUnmounted, computed, getCurrentInstance, reactive } from 'vue';
	import { onLoad, onShow, onUnload } from "@dcloudio/uni-app";
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();

	import { useMainStore, useInventoryStore, useUserStore, usePermissionStore } from '@/store';
	const inventoryStore = useInventoryStore();
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();

	// 类型定义
	interface Config {
		tabbarHeight : number;
		scrollHeight : number;
	}

	const { config = {
		tabbarHeight: 0,
		scrollHeight: 500
	}, isPage = true } = defineProps(['config', 'isPage'])
	console.log(isPage);

	// 计算页面配置信息，根据是否为独立页面设置不同的滚动高度
	const pageConfig = computed(() => {
		const configInfo = uni.$utils.deepClone(config);
		// 根据页面类型设置滚动高度
		configInfo.scrollHeight = isPage ? '100vh' : `${config.scrollHeight}px`;

		return configInfo;
	});

	const approveWaitToOpenNext = computed(() => {
		return inventoryStore.st_comPageConfig.approveWaitToOpenNext;
	})
	function switchChange(e : any) {
		console.log(e);

		inventoryStore.st_comPageConfig.approveWaitToOpenNext = e.detail.value;
	}

	let searchKey = ref("");
	function search() {
		paging.value.reload();
	};
	function refreshPage() {
		search()
	};
	function searchScanBtn() {
		uni.$utils.$scanPopup.openScan({
			success: (res : any) => {
				searchKey.value = res.result;
				refreshPage();
			}
		})
	};

	const tabList = ref([
		{
			name: '待我处理',
			badge: {
				count: 0
			},
		},
		{
			name: '我已处理',
			badge: {
				count: 0
			},
		},
		{
			name: '我创建的',
			badge: {
				count: 0
			},
		},
		{
			name: '相关审批',
			badge: {
				count: 0
			},
		}
	]);
	interface pagingInstance {
		reload : () => void;
		refresh : () => void;
		complete : () => void;
		refreshToPage : () => void;
		setLocalPaging : () => void;
	};
	let paging = ref<pagingInstance | any>(null);
	let tableData = ref<any>([])
	let current = ref(0);
	function tabsChange() {

	};
	let source = ref<any>(null);
	// 自定义默认时间
	let DropDowmMenu_Date = reactive({
		DateTitle: "",
		SDate: "",
		EDate: "",
	});
	Object.assign(DropDowmMenu_Date, {
		DateTitle: "",
		SDate: uni.$utils.getDateAfterNDays(-10),
		EDate: uni.$utils.getDateAfterNDays(0),
	});
	interface filterMenuInstance {
		open : () => void;
		close : () => void;
	};
	let filterMenu = ref<filterMenuInstance | any>(null)
	function DateSubmit(e : any) {
		console.log(e);
		Object.assign(DropDowmMenu_Date, e);
		filterMenu.value.close();
		paging.value.reload();
	}
	function onDateReset() {
		Object.assign(DropDowmMenu_Date, {
			SDate: "",
			EDate: ""
		});

		filterMenu.value.close()
		paging.value.reload();
	}

	const UserInfo = userStore.UserInfo;
	let tableData_all = ref<any>([]);
	// 获取待办数据
	function getTableDataFun() {
		uni.$utils.showLoading();

		try {

			request({
				config: {
				},
				url: 'APP_MessageToDoRemind',
				method: 'POST',
				data: {
					StartTime: DropDowmMenu_Date.SDate,
					EndTime: DropDowmMenu_Date.EDate,
					searchKey: searchKey,
					UserID: UserInfo.UserID,
					MSGType: 1,
					source: source.value,
				},
				success(ret : any) {
					console.log(ret);
					if (ret.status == 200) {
						let data = processArray(ret.data);
						tableData_all.value = data;
						tabList.value[0].badge.count = data[0].length;
						paging.value.setLocalPaging(data[current.value]);
						uni.$utils.hideLoading();
					} else {
						uni.$utils.hideLoading();
					}
				},
				fail(err : any) {
					paging.value.setLocalPaging(false);
					uni.$utils.hideLoading();
				}
			});
		} catch (error) {
			paging.value.setLocalPaging(false);
			uni.$utils.hideLoading();
		}

	};
	function processArray(input : object) {
		// 将输入对象转换为一个数组，只包含值
		return Object.values(input).map(item => {

			if (uni.$utils.isEmpty(item)) {
				return []
			}
			return item; // 如果是数组，则直接返回
		});
	};
	// 记录选中数据
	let choiceRow = ref<any>({});
	function getNextItemById() {
		let choiceRowIfno = uni.$utils.deepClone(choiceRow.value);
		// 找到当前 id 对应的索引
		const currentIndex = tableData.value.findIndex((item : { AuditID : number }) => item.AuditID === choiceRowIfno.AuditID);
		let listType = 'next';
		let nextData = [];
		if (currentIndex == -1 || currentIndex == tableData.value.length - 1) {
			// 如果未找到当前 id 的数据，返回 null
			if (currentIndex == -1) {
				listType = 'null';
			}
			if (currentIndex == tableData.value.length - 1) {
				listType = 'lastData';
			};

		} else {
			nextData = tableData.value[currentIndex + 1];

			choiceRow.value = uni.$utils.deepClone(nextData);
		}

		let obj = {
			listType: listType,
			nextData: nextData,
		};


		uni.$emit("emitNextItem", obj); // 向详情页发送处理后的数据
	}

	onLoad((option : any) => {
		if (!uni.$utils.isEmpty(option) && option.source) {
			source.value = option.source;
		};
		getTableDataFun();
	});

	onMounted(() => {
		uni.$on('ApproveScanCode', function (content) {
			uni.$utils.showLoading('正在解码');
			searchKey.value = content;
			refreshPage();
		})

		// 用于接收审批待办打开的详情页触发下一条的指令
		uni.$on('switch-to-next-item', function (data) {
			if (current.value == 0 && approveWaitToOpenNext.value) { // 只有待我处理才会触发
				getNextItemById();
			}
		})
	});
	onUnload(() => {
		uni.$off('ApproveScanCode');
		uni.$off('refreshToApprove');
		uni.$off('switch-to-next-item');
	})
</script>

<style lang="scss" scoped>
	$h-padding: 5px;
	$v-padding: 10px;
	$radius: 5px;

	.pageContent {
		background-color: #f2f1f6;
	}


	.MenuSelect {
		display: flex;
		align-items: center;
		margin-left: 8px;
		padding: 0 10px;
		height: 35px;
		font-size: 16px;
		font-weight: 500;
		background-color: rgba(0, 0, 0, .03) !important;
		border-radius: $radius;

		.text {
			font-size: 14px;
			margin-right: 5px
		}
	}

	.search {
		background-color: #fff;
		background-color: #51d0d0;
		padding: 6px 10px;

		.scanQrCode {
			width: 20rpx;
			padding: 5rpx;
		}

		.MenuText {
			font-size: 14px;
			border-right: 1px solid #999;
			padding-right: 10px;
			margin-right: 4px;
		}
	}

	.MenuBoxMax {
		position: relative;
		height: 42px;
		width: 100%;
		border-bottom: 4px solid #f2f2f2;

		.MenuBox {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			background-color: #fff;

			.selectSearchDom {
				padding-right: 10rpx;
			}
		}
	}

	.CardBox {
		position: relative;
		border-radius: 16rpx;
		padding: 24rpx;
		background: #ffffff;
		transition: all 0.2s ease;
		margin-bottom: 20rpx;

		/* 新增激活状态 */
		&:active {
			transform: scale(0.98);
			background: #f8fdff;
		}

		&-top {
			display: flex;
			align-items: flex-start;
			justify-content: space-between;
			margin-bottom: 16rpx;

			&_left {
				display: flex;
				align-items: flex-start;
				gap: 12rpx;

				/* 序号样式优化 */
				&_ordinal {
					flex-shrink: 0;
					background: linear-gradient(135deg, #51d0d0, #2ab5b5);
					color: #fff;
					font-size: 24rpx;
					padding: 4rpx 12rpx;
					border-radius: 8rpx;
					line-height: 1.4;
				}

				/* 标题容器 */
				&_title {
					flex: 1;
					min-width: 0;

					text {
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
						overflow: hidden;
						font-size: 32rpx;
						color: #333;
						line-height: 1.4;
					}
				}
			}

			&_right {
				flex-shrink: 0;

				&_title {
					font-size: 24rpx;
					color: #999;
					padding: 4rpx 12rpx;
					background: #f5f5f5;
					border-radius: 8rpx;
					white-space: nowrap;
				}
			}
		}

		&_content {
			font-size: 28rpx;
			color: #666;
			line-height: 1.6;
			margin: 16rpx 0;
			min-height: 80rpx;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 3;
			overflow: hidden;
			position: relative;

			/* 添加渐变遮罩 */
			// &::after {
			// 	content: '';
			// 	position: absolute;
			// 	bottom: 0;
			// 	left: 0;
			// 	right: 0;
			// 	height: 40rpx;
			// 	background: linear-gradient(to bottom, rgba(255, 255, 255, 0), #fff 80%);
			// 	pointer-events: none;
			// }
		}

		&_bottom {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 24rpx;
			color: #999;
			padding-top: 16rpx;
			border-top: 1rpx solid #eee;

			&_right {
				flex-shrink: 0;

				&_title {
					font-size: 24rpx;
					color: #999;
					padding: 4rpx 12rpx;
					// background: #f5f5f5;
					border-radius: 8rpx;
					white-space: nowrap;
				}
			}
		}
	}
</style>